package com.xoa.dev.qywx.service;

import com.google.gson.internal.$Gson$Preconditions;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.qiyeWeixin.QiyeWeixinConfigMapper;
import com.xoa.dao.qiyeWeixin.UserWeixinqyMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dev.qywx.model.QywxUser;
import com.xoa.model.department.Department;
import com.xoa.model.modulePriv.ModulePriv;
import com.xoa.model.qiyeWeixin.QiyeWeixinConfig;
import com.xoa.model.qiyeWeixin.UserWeixinqy;
import com.xoa.model.users.UserExt;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.service.department.DepartmentService;
import com.xoa.service.qyweixin.QiyeWeixinService;
import com.xoa.service.users.UsersService;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.http.HttpClientUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.cxf.wsdl.http.UrlEncoded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;


@Service
public class QywxService {


    // 企业微信配置service
    @Autowired
    private QiyeWeixinService qywxConfigService;

    @Autowired
    private UserWeixinqyMapper userWeixinqyMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private QiyeWeixinConfigMapper qiyeWeixinConfigMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private UserPrivMapper userPrivMapper;

    @Autowired
    private UsersService usersService;

    @Autowired
    private DepartmentService departmentService;


    // -------------------------变量区---------------------------- //

    // 企业凭证
    private String ACCESS_TOKEN = "";
    // 第三方应用凭证（suite_access_token）
    private String SUITE_ACCESS_TOKEN = "";
    // 第三方应用suite_ticket
    private String SUITE_TICKET = "";

    // accessToken 生成时间（两个小时有效期
    private Long accessToken_TimeLimit = new Date().getTime();
    // suiteAccessToken 生成时间（两个小时有效期
    private Long suiteAccessToken_TimeLimit = new Date().getTime();

    // -------------------------变量区---------------------------- //


    public String getAccessToken(){
        Long CurTimeLimit = new Date().getTime();
        if(ACCESS_TOKEN == "" || (CurTimeLimit-accessToken_TimeLimit)/1000 >7000){
            QiyeWeixinConfig qiyeWeixinConfig = qiyeWeixinConfigMapper.selectConfig();
            JSONObject res = HttpClientUtil.httpGet(qiyeWeixinConfig.getApiDomain()+"/cgi-bin/gettoken?corpid="+qiyeWeixinConfig.getCorpid()+"&corpsecret="+qiyeWeixinConfig.getCorpsecret());
            if((Integer)res.get("errcode") == 0){
                ACCESS_TOKEN = (String) res.get("access_token");
            }
        }
        return ACCESS_TOKEN;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/24
     * @说明: 获取SUITE_ACCESS_TOKEN 用于第三方应用授权等接口调用
     */
    public String getSuiteAccessToken(){
        // 获取数据库中的配置信息 获取suite_id suite_secret
        BaseWrapper configBaseWrapper = qywxConfigService.getQiyeWeixinConfig();
        QiyeWeixinConfig data = (QiyeWeixinConfig) configBaseWrapper.getData();

        Long CurTimeLimit = new Date().getTime();
        if(SUITE_ACCESS_TOKEN == "" || (CurTimeLimit-suiteAccessToken_TimeLimit)/1000 >7000){
            JSONObject res = HttpClientUtil.httpGet(data.getApiDomain()+"/cgi-bin/service/get_suite_token?suite_id="+data.getSuiteId()+"&suite_secret="+data.getSuiteSecret()+"&suite_ticket="+SUITE_TICKET);
            if((Integer)res.get("errcode") == 0){
                SUITE_ACCESS_TOKEN = (String) res.get("suite_access_token");
            }
        }
        return SUITE_ACCESS_TOKEN;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/24
     * @说明: 获取suiteTicket 用于接收服务器中推送的suiteTicket
     */
    public void receiveSuiteTicket(String SuiteId,String InfoType,String TimeStamp,String SuiteTicket){

        if(!StringUtils.checkNull(SuiteTicket)){
            SUITE_TICKET = SuiteTicket;
        }

    }

    public JSONObject getWxUserByCode(String code){
        JSONObject res = null;
        if(!StringUtils.checkNull(code)){
            res = HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/user/getuserinfo?access_token="+getAccessToken()+"&code="+code);

        }
        return res;
    }

    public String getJsapiTicket(){
        JSONObject res = HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/get_jsapi_ticket?access_token="+getAccessToken());
        if((Integer)res.get("errcode") == 0){
            return (String) res.get("ticket");
        }
        return "";
    }

    public String getJsapiTicketByagent(){
        JSONObject res = HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/ticket/get?access_token="+getAccessToken()+"&type=agent_config");
        if((Integer)res.get("errcode") == 0){
            return (String) res.get("ticket");
        }
        return "";
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/24
     * @说明: 企业微信授权登陆 (进行中，未完成，完成后删除这条信息)
     */
    public JSONObject OAuth2Login(String code){
        JSONObject res = null;

        if(!StringUtils.checkNull(code)){

            // 获取suiteAccessToken
            String suiteAccessToken = getSuiteAccessToken();

            // 获取当前登陆用户信息
            res = HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/service/getuserinfo3rd?access_token="+suiteAccessToken+"&code="+code);

            if((Integer)res.get("errcode")==0){

                return res;
            }
        }

        return res;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/24
     * @说明: 获取企业微信中的部门信息 id为部门id 填写获取指定部门 不填写获取全部部门
     */
    public JSONObject getDepartments(String id){
        if(id==null)
            return HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/department/list?access_token=" + getAccessToken());
        return HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/department/list?access_token=" + getAccessToken() + "&id=" + id);
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/24
     * @说明: 获取指定部门下的用户信息 不填写获取全部部门下的用户信息
     */
    public List<QywxUser> getUsersByDept(String id){
        List<QywxUser> resList = null;

        // 获取部门信息
        JSONObject deptJson = getDepartments(id);
        // 判断部门信息获取是否成功
        if((Integer)deptJson.get("errcode")==0){
            resList = new ArrayList<QywxUser>();

            JSONArray departments = deptJson.getJSONArray("department");

            for (int i=0,size=departments.size();i<size;i++){
                JSONObject department = departments.getJSONObject(i);

                JSONObject res = HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/user/simplelist?access_token=" + getAccessToken() + "&department_id=" + department.getString("id"));

                if((Integer)res.get("errcode")==0){
                    JSONArray userlist = res.getJSONArray("userlist");
                    if(userlist.size()>0) {
                        for (int j = 0, size2 = userlist.size(); j < size2; j++) {
                            JSONObject jsonObject = userlist.getJSONObject(j);
                            QywxUser qywxUser = new QywxUser();
                            qywxUser.setUserid(jsonObject.getString("userid"));
                            qywxUser.setName(jsonObject.getString("name"));
                            resList.add(qywxUser);
                        }
                    }
                }
            }

        }

        return resList;
    }


    /**
     * @作者: 张航宁
     * @时间: 2019/6/24
     * @说明: 获取指定部门下的用户信息 不填写获取全部部门下的用户信息 详情
     */
    public List<QywxUser> getUsersDetailByDept(String id){
        List<QywxUser> resList = new ArrayList<>();
        JSONObject res = HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/user/list?fetch_child=0&access_token=" + getAccessToken() + "&department_id=" + id);
        if("0".equals(res.getString("errcode"))){
            JSONArray userlist = res.getJSONArray("userlist");
            if(userlist.size()>0) {
                for (int j = 0, size2 = userlist.size(); j < size2; j++) {
                    JSONObject jsonObject = userlist.getJSONObject(j);
                    QywxUser qywxUser = new QywxUser();
                    qywxUser.setUserid(jsonObject.getString("userid"));
                    qywxUser.setName(jsonObject.getString("name"));
                    qywxUser.setGender(jsonObject.getString("gender"));
                    qywxUser.setMobile(jsonObject.getString("mobile"));
                    qywxUser.setPosition(jsonObject.getString("position"));
                    qywxUser.setEmail(jsonObject.getString("email"));
                    JSONArray departmentJSONArr = jsonObject.getJSONArray("department");
                    String[] department = new String[departmentJSONArr.size()];
                    for (int i = 0; i < departmentJSONArr.size(); i++) {
                        department[i] = departmentJSONArr.get(i).toString();
                    }
                    qywxUser.setDepartment(department);
                    resList.add(qywxUser);
                }
            }
        } else {
            System.out.println("line 261:id:"+id);
            System.out.println("line 262:errcode:"+res.getString("errcode"));
            System.out.println("line 263:errmsg:"+res.getString("errmsg"));
            System.out.println();
        }

        return resList;
    }



    /**
     * @作者: 张航宁
     * @时间: 2019/6/24
     * @说明: 根据userid获取企业微信中的用户信息
     */
    public JSONObject getUserByUserid(String userid){
       return  HttpClientUtil.httpGet(getConfig().getApiDomain()+"/cgi-bin/user/get?access_token="+getAccessToken()+"&userid="+userid);
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/25
     * @说明: 查询所有用户和绑定状态
     */
    public BaseWrapper selUsersWithBindType(String deptId){
        BaseWrapper baseWrapper = new BaseWrapper();

        List<QywxUser> usersByDept = getUsersByDept(deptId);

        List<UserWeixinqy> userWeixinqies = userWeixinqyMapper.selAllBindUsers();

        Map<String,String> bindMap = new HashMap<String,String>();

        List<UserWeixinqy> resList = new ArrayList<>();
        for(int i=0,size=userWeixinqies.size();i<size;i++){
            UserWeixinqy userWeixinqy = userWeixinqies.get(i);
            if(userWeixinqy!=null){
                bindMap.put(userWeixinqy.getOpenId(),userWeixinqy.getUserId());
                userWeixinqy.setIfBind("1");
            }
        }

        for(int i=0,size=usersByDept.size();i<size;i++){
            QywxUser qywxUser = usersByDept.get(i);
            // 1.判断是否为空 2.判断企业微信中的用户的userid是否为空 3.判断是否已经是绑定过的用户
            if(qywxUser!=null&&!StringUtils.checkNull(qywxUser.getUserid())&&bindMap.get(qywxUser.getUserid())==null){
                UserWeixinqy userWeixinqy = new UserWeixinqy();
                userWeixinqy.setOpenId(qywxUser.getUserid());
                userWeixinqy.setUserName(qywxUser.getName());
                userWeixinqy.setIfBind("0");
                resList.add(userWeixinqy);
            }else if(qywxUser!=null&&bindMap.get(qywxUser.getUserid())!=null){
                UserWeixinqy userWeixinqy = new UserWeixinqy();
                userWeixinqy.setOpenId(qywxUser.getUserid());
                userWeixinqy.setUserName(qywxUser.getName());
                userWeixinqy.setIfBind("1");
                userWeixinqy.setUserId(bindMap.get(qywxUser.getUserid()));
                String usernameByUserId = usersMapper.getUsernameByUserId(userWeixinqy.getUserId());
                if(!StringUtils.checkNull(usernameByUserId)){
                    userWeixinqy.setBindUserName(usernameByUserId);
                } else {
                    userWeixinqy.setBindUserName("该用户不存在");
                }
                resList.add(userWeixinqy);
            }
        }

        baseWrapper.setData(resList);
        baseWrapper.setFlag(true);
        return baseWrapper;
    }


    /**
     * @作者: 张航宁
     * @时间: 2019/6/24
     * @说明: 获取企业微信中的用户数据id 绑定OA中的用户
     */
    public BaseWrapper bind(String openId,String userId){
        BaseWrapper baseWrapper = new BaseWrapper();

        if(!StringUtils.checkNull(openId)&&!StringUtils.checkNull(userId)){
            // 根据OaUserId判断是否存在 更新信息
            UserWeixinqy userid1 = userWeixinqyMapper.selUserByUserId(userId);
            if (userid1==null) {
                // 根据openId判断是否存在，更新信息
                UserWeixinqy userWeixinqy = userWeixinqyMapper.selUserByOpenId(openId);
                if(userWeixinqy==null){
                    userWeixinqy = new UserWeixinqy();
                    userWeixinqy.setUserId(userId);
                    userWeixinqy.setOpenId(openId);
                    userWeixinqy.setDeviceid("");
                    userWeixinqy.setIsSys((byte) 0);
                    userWeixinqyMapper.insertSelective(userWeixinqy);
                } else {
                    userWeixinqy.setOpenId(openId);
                    userWeixinqy.setUserId(userId);
                    userWeixinqyMapper.updateUserByOpenId(userWeixinqy);
                }
            }else{
                userid1.setUserId(userId);
                userid1.setOpenId(openId);
                userWeixinqyMapper.updateUserByUserId(userid1);
            }

            baseWrapper.setFlag(true);
            baseWrapper.setMsg("绑定成功");
        }else {
            baseWrapper.setFlag(false);
            baseWrapper.setMsg("绑定失败，openId或者userId为空");
        }

        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/25
     * @说明: 解除绑定接口
     */
    public BaseWrapper removeBind(String openId,String userId){
        BaseWrapper baseWrapper = new BaseWrapper();
        if(!StringUtils.checkNull(userId)&&!StringUtils.checkNull(openId)){
            userWeixinqyMapper.deleteByOpenIdOrUserId(openId,userId);
            baseWrapper.setMsg("解绑成功");
            baseWrapper.setFlag(true);
        }else{
            baseWrapper.setMsg("openId和userId为空，解绑失败");
            baseWrapper.setFlag(false);
        }

        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/1
     * @说明: 连接测试
     */
    public BaseWrapper testConnect(){
        BaseWrapper baseWrapper = new BaseWrapper();
        String accessToken = getAccessToken();
        if(!StringUtils.checkNull(accessToken)){
            baseWrapper.setMsg("连接成功");
            baseWrapper.setFlag(true);
        }else{
            baseWrapper.setMsg("连接失败");
            baseWrapper.setFlag(false);
        }
        return baseWrapper;
    }



    /**
     * @作者: 张航宁
     * @时间: 2019/8/7
     * @说明: 获取config信息
     */
    public QiyeWeixinConfig getConfig(){
        return qiyeWeixinConfigMapper.selectConfig();
    }


    /**
     * @作者: 张航宁
     * @时间: 2019/12/18
     * @说明: 企业微信应用推送消息接口
     * 为了跳转指定详情页设置为openType为要跳转的url,转码进行跳转
     */
    public BaseWrapper sendMsg(List<String> userIds, String title, String content,String openType, Boolean allType) {
        BaseWrapper baseWrapper = new BaseWrapper();
        baseWrapper.setFlag(false);
        // 企业微信配置
        QiyeWeixinConfig config = getConfig();
        if(config==null){
            baseWrapper.setMsg("配置信息为空");
            return baseWrapper;
        }else{
            String accessToken = getAccessToken();
            if(StringUtils.checkNull(accessToken)){
                baseWrapper.setMsg("配置信息有误，连接企业微信失败");
                return baseWrapper;
            }
            if (StringUtils.checkNull(config.getAgentid())){
                baseWrapper.setMsg("没有设置应用id，发送失败");
                return baseWrapper;
            }
        }

        // 推送消息的url
        String url = getConfig().getApiDomain()+"/cgi-bin/message/send?access_token="+getAccessToken();

        // touser 设置初始化
        String touser = "";
        if(allType!=null&&allType){
            touser = "@all";
        } else {
            // 推送消息人员处理
            List<UserWeixinqy> userWeixinqies = userWeixinqyMapper.selUsersByUserIds(userIds);
            // 判断是否有值
            if(userWeixinqies==null||userWeixinqies.size()<=0){
                baseWrapper.setMsg("发送人员没有进行企业微信绑定，无法获取企业微信userId进行发送");
                return baseWrapper;
            }

            for (int i = 0; i < userWeixinqies.size(); i++) {
                UserWeixinqy userWeixinqy = userWeixinqies.get(i);
                String openId = userWeixinqy.getOpenId();
                if(!StringUtils.checkNull(openId)){
                    touser+=openId+"|";
                }
            }
        }

        // 消息具体内容
        JSONObject textCard = new JSONObject();
        textCard.put("title",title);
        textCard.put("description",content);
        textCard.put("btntxt","更多");


        String url2 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ config.getCorpid()
                +"&redirect_uri="+ URLEncoder.encode(config.getOaUrl()+"/ewx/m/main?openType="+URLEncoder.encode(openType))
                +"&response_type=code&scope=snsapi_base&agentid="+config.getAgentid()
                +"#wechat_redirect";

        if(!config.getApiDomain().contains("qyapi.weixin.qq.com")){
            url2 = config.getApiDomain() + "/connect/oauth2/authorize?appid="+ config.getCorpid()
                    +"&redirect_uri="+ URLEncoder.encode(config.getOaUrl()+"/ewx/m/main?openType="+URLEncoder.encode(openType))
                    +"&response_type=code&scope=snsapi_base&agentid="+config.getAgentid()
                    +"#wechat_redirect";
        }

        textCard.put("url",url2);

        // 基本参数
        Map<String,String> data = new HashMap<>();
        data.put("touser",touser);
        data.put("msgtype","textcard");
        data.put("agentid", config.getAgentid());
        data.put("textcard",textCard.toString());

        JSONObject jsonObject = JSONObject.fromObject(HttpClientUtil.doPost(url, data, "UTF-8"));

        if((Integer)jsonObject.get("errcode")==0){
            baseWrapper.setFlag(true);
            baseWrapper.setMsg("发送成功");
        }else{
            baseWrapper.setMsg("发送失败，errcode："+jsonObject.get("errcode"));
        }
        return baseWrapper;
    }

    /**
     * @接口说明: 企业微信同步组织接口
     * @日期: 2020/3/18
     * @作者: 张航宁
     */
    public void WxDeptToOA(){
        JSONObject departments = getDepartments("0");
        if(departments!=null&&departments.getString("errcode").equals("0")){
            JSONArray department = departments.getJSONArray("department");
            for (int i = 0; i < department.size(); i++) {
                JSONObject jsonObject = department.getJSONObject(i);
                insertDept(jsonObject);
            }
            departmentService.updateDeptNo(0,"");
        }
    }

    /**
     * @接口说明: 企业微信同步用户信息
     * @日期: 2020/3/19
     * @作者: 张航宁
     */
    public void WxUserToOA(HttpServletRequest request){
        // 获取所有部门
        JSONObject departments = getDepartments("0");
        if(departments!=null&&departments.getString("errcode").equals("0")){
            JSONArray department = departments.getJSONArray("department");
            // 循环部门
            for (int i = 0; i < department.size(); i++) {
                JSONObject jsonObject = department.getJSONObject(i);
                String id = jsonObject.getString("id");
                // 根据企业微信的部门id获取部门
                Department departmentWx = departmentMapper.getDeptByWxDeptId(id);
                // 如果部门为空的话 插入部门
                if(departmentWx==null){
                    insertDept(jsonObject);
                    departmentWx = departmentMapper.getDeptByWxDeptId(id);
                    if(departmentWx!=null){
                        insertUser(request, id, departmentWx);
                    }
                } else {
                    // 插入或者更新用户
                    insertUser(request, id, departmentWx);
                }
            }
        }
    }

    /**
     * @接口说明: 插入用户
     * @日期: 2020/3/19
     * @作者: 张航宁
     */
    private void insertUser(HttpServletRequest request, String id, Department departmentWx) {
        UserPriv minNoUserPriv = userPrivMapper.getMinNoUserPriv();
        List<QywxUser> qywxUsers = getUsersDetailByDept(id);
        for (QywxUser qywxUser : qywxUsers) {
            Users users = new Users();
            users.setByname(qywxUser.getMobile());// 登录账户名
            users.setUserName(qywxUser.getName());
            users.setDeptId(departmentWx.getDeptId());
            users.setDeptName(departmentWx.getDeptName());
            users.setSex(qywxUser.getGender().equals("1") ? "0" : "1");
            users.setMobilNo(qywxUser.getMobile());
            users.setEmail(qywxUser.getEmail());
            users.setOicqNo(qywxUser.getUserid());
            List<UserPriv> userPrivsByName = userPrivMapper.getUserPrivsByName(qywxUser.getPosition().trim());
            if (userPrivsByName != null && userPrivsByName.size() > 0) {
                for (UserPriv userPriv : userPrivsByName) {
                    users.setUserPriv(userPriv.getUserPriv());
                    users.setUserPrivName(userPriv.getPrivName());
                    break;
                }
            } else {
                users.setUserPriv(minNoUserPriv.getUserPriv());
                users.setUserPrivName(minNoUserPriv.getPrivName());
            }
            // 辅助部门
            String[] department = qywxUser.getDepartment();
            StringBuilder deptOther = new StringBuilder();
            for (String wxDeptId:department) {
                Department departmentWxOther = departmentMapper.getDeptByWxDeptId(wxDeptId);
                if(departmentWxOther!=null){
                    deptOther.append(departmentWxOther.getDeptId()).append(",");
                }
            }
            users.setDeptIdOther(deptOther.toString());
            // 设置其他默认信息
            users.setPassword("");
            users.setTheme((byte) 6);
            users.setPostPriv("0");
            users.setNotLogin((byte) 0);
            // 插入用户
            Users usersBybyname = usersMapper.getUsersBybyname(users.getByname());
            if (usersBybyname == null) {
                ToJson<Users> usersToJson = usersService.addUser(users, new UserExt(), new ModulePriv(), request);
                if (usersToJson.isFlag()) {
                    Users users1 = (Users) usersToJson.getObject();
                    UserWeixinqy userWeixinqy = userWeixinqyMapper.selUserByOpenId(qywxUser.getUserid());
                    if (userWeixinqy == null) {
                        userWeixinqy = new UserWeixinqy();
                        userWeixinqy.setOpenId(qywxUser.getUserid());
                        userWeixinqy.setUserId(users1.getUserId());
                        userWeixinqy.setIsSys((byte) 0);
                        userWeixinqy.setDeviceid("");
                        userWeixinqyMapper.insertSelective(userWeixinqy);
                    }
                }
            }
        }
    }

    /**
     * @接口说明: 递归插入部门 由低级向上级遍历
     * @日期: 2020/3/19
     * @作者: 张航宁
     */
    private void insertDept(JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        String parentid = jsonObject.getString("parentid");
        String name = jsonObject.getString("name");
        // 查询当前部门
        Department departmentWx = departmentMapper.getDeptByWxDeptId(id);
        // 判断是否存在当前部门
        if(departmentWx==null){
            // 如果不存在 判断他是否是最外级的部门
            if(!"0".equals(parentid)){
                // 不是最外级别的部门 查询他的父级别部门是否存在
                Department departmentWxParent = departmentMapper.getDeptByWxDeptId(parentid);
                // 不存在进行递归向上获取
                if(departmentWxParent==null){
                    JSONObject departments = getDepartments(String.valueOf(parentid));
                    if(departments!=null&&departments.getString("errcode").equals("0")){
                        JSONArray department = departments.getJSONArray("department");
                        for (int i = 0; i < department.size(); i++) {
                            JSONObject jsonObject1 = department.getJSONObject(i);
                            if(jsonObject1.getString("id").equals(parentid)){
                                insertDept(jsonObject1);
                            }
                        }
                    }
                } else {  // 存在执行插入操作
                    departmentWx = new Department();
                    departmentWx.setWeixinDeptId(id);
                    departmentWx.setDeptName(name);
                    departmentWx.setDeptParent(departmentWxParent.getDeptId());
                    departmentMapper.insertDept(departmentWx);
                }
            } else {
                // 插入 departmentWx
                departmentWx = new Department();
                departmentWx.setWeixinDeptId(id);
                departmentWx.setDeptName(name);
                departmentWx.setDeptParent(0);
                departmentMapper.insertDept(departmentWx);
            }
        } else {
            // 如果存在 查看名称是否不同 是否需要进行更新
            if(!StringUtils.checkNull(name)&&!name.equals(departmentWx.getDeptName())){
                departmentWx.setDeptName(name);
                departmentMapper.editDept(departmentWx);
            }
        }
    }

    public BaseWrapper mobileBindOAUser(){
        BaseWrapper baseWrapper = new BaseWrapper();
        // 获取所有部门
        JSONObject departments = getDepartments("0");
        if(departments!=null&&departments.getString("errcode").equals("0")){
            JSONArray department = departments.getJSONArray("department");
            // 循环部门
            for (int i = 0; i < department.size(); i++) {
                JSONObject jsonObject = department.getJSONObject(i);
                String id = jsonObject.getString("id");
                List<QywxUser> usersDetailByDept = getUsersDetailByDept(id);
                usersDetailByDept.forEach((qywxUser)->{
                    Users users = usersMapper.selectByPhoneAndName(qywxUser.getName(), qywxUser.getMobile());
                    if(users!=null&&!StringUtils.checkNull(users.getUserId())){
                        bind(qywxUser.getUserid(),users.getUserId());
                    } else {
                        Users users1 = usersMapper.selectUserAllInfoByName(qywxUser.getMobile());
                        if(users1!=null&&!StringUtils.checkNull(users1.getUserId())){
                            bind(qywxUser.getUserid(),users1.getUserId());
                        }
                    }
                });
            }
        }
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }


}
